package com.emm.yixun.website.controller.call;
//框架包
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;



//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.model.User;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
//变化的引用
import com.emm.yixun.common.model.ImportError;
import com.emm.yixun.common.model.dto.ImportErrorDto;
import com.emm.yixun.common.model.dto.PriceSchemeView;
import com.emm.yixun.customer.service.ImportErrorServiceFacade;




@Controller
@RequestMapping("/call/importError/")
public class ImportErrorController extends BaseController<ImportError>{
	
	@Autowired
	private ImportErrorServiceFacade importErrorServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));		
			return "/customer/importError/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(ImportErrorDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:importError:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<ImportErrorDto> response=importErrorServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:importError:view"))){
        	try {
				Response<ImportError> response=importErrorServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(ImportErrorDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:importError:edit"))){
        	try {
        		Response<Integer> response=importErrorServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:importError:delete"))){
        	try {
        		Response<Integer> response=importErrorServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ImportErrorDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:importError:list"))){
        	try {
        		Page<ImportError> response=importErrorServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<ImportError>());
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	@RequestMapping(value = "download")
	public void downloadExcelModel(ImportErrorDto dto,HttpServletResponse response){
		try {
			  @SuppressWarnings("resource")
			  HSSFWorkbook wb = new HSSFWorkbook();  
			  HSSFSheet sheet = wb.createSheet("出错客户");  
			  HSSFCellStyle headStyle = wb.createCellStyle(); 
			  HSSFFont f  = wb.createFont();      
			  f.setFontHeightInPoints((short) 11);// 字号   
		      f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗   
		      headStyle.setFont(f); 
		      headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
		      headStyle.setBorderBottom((short) 1);
		      headStyle.setBorderRight((short) 1);
		      headStyle.setFillBackgroundColor((short) 20);
		      HSSFRow row = sheet.createRow((int) 0); 
		      //创建单元格，并设置值表头 设置表头居中  
		      HSSFCellStyle style = wb.createCellStyle();  
		      style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
		      style.setBorderBottom((short) 1);
		      style.setBorderRight((short) 1);
		      String[] header = new String[]{"客户姓名","联系电话","说明","失败原因"};
		      for (int i = 0; i < header.length; i++)  {  
		            HSSFCell cell = row.createCell(i);  
		            cell.setCellStyle(style);  
		            HSSFRichTextString text = new HSSFRichTextString(header[i]);  
		            cell.setCellValue(text);  
		      }  
		      ResponseList<ImportError> ieListResponse=importErrorServiceFacade.findByDto(dto);
		      if(ieListResponse.isSuccess() && ieListResponse.getEntity()!=null && ieListResponse.getEntity().size()>0){
		    	  HSSFCell cell = null;
		    	  for (int j = 0; j < ieListResponse.getEntity().size(); j++) {
		    		  row = sheet.createRow((int) j + 1);  
		    		  ImportError importError =  ieListResponse.getEntity().get(j);  
		    		  cell = row.createCell(0,1);
		              cell.setCellValue(StringUtils.isBlank(importError.getUserName())?"":importError.getUserName());
		              cell = row.createCell(1,1);
		              cell.setCellValue(StringUtils.isBlank(importError.getPhone())?"":importError.getPhone());
		              cell = row.createCell(2,1);
		              cell.setCellValue(StringUtils.isBlank(importError.getRemark())?"":importError.getRemark());
		              cell = row.createCell(3,1);
		              cell.setCellValue(importError.getFailure());
				}
		      }

		      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		      String mimetype = "application/x-msdownload";
		      String downFileName = "excel-"+df.format(new Date())+".xls";
		      String inlineType = "attachment"; 
		      response.setHeader("Content-Disposition", inlineType  + ";filename=\"" + downFileName + "\"");
		      OutputStream out=response.getOutputStream();
		      response.setContentType(mimetype);
		      wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
